package com.laob.laob_special.util;

import com.alibaba.fastjson.JSONObject;
import com.laob.laob_special.util.custom.MyStrignUtils;
import org.apache.http.*;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.io.Console;
import java.io.IOException;
import java.util.Arrays;
import java.util.Map;
import java.util.Set;

/**
 * @author zhangh     
 * @version V1.0.0
 * @projectName laob_special
 * @title     HttpClientUtils   
 * @package    com.laob.laob_special.util  
 * @date   2019/9/9 18:29  
 * @explain
 */
@SuppressWarnings("all")
public class HttpClientUtils {

    private static Logger logger = LoggerFactory.getLogger(HttpClientUtils.class); // 日志记录

    private static RequestConfig requestConfig = null;

    static {
        // 设置请求和传输超时时间
        requestConfig = RequestConfig.custom().setSocketTimeout(6000).setConnectTimeout(6000).build();
    }

    /**
     * post请求传输json参数
     *
     * @param url url地址
     * @return
     */
    public static JSONObject httpPost(String url, JSONObject jsonParam) {
        // post请求返回结果
        CloseableHttpClient httpClient = HttpClients.createDefault();
        JSONObject jsonResult = null;
        HttpPost httpPost = new HttpPost(url);
        // 设置请求和传输超时时间
        httpPost.setConfig(requestConfig);
        try {
            if (null != jsonParam) {
                // 解决中文乱码问题
                StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");
                entity.setContentEncoding("UTF-8");
                entity.setContentType("application/json");
                httpPost.setEntity(entity);
            }
            CloseableHttpResponse result = httpClient.execute(httpPost);
            // 请求发送成功，并得到响应
            if (result.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                String str = "";
                try {
                    // 读取服务器返回过来的json字符串数据
                    str = EntityUtils.toString(result.getEntity(), "utf-8");
                    // 把json字符串转换成json对象
                    jsonResult = JSONObject.parseObject(str);
                } catch (Exception e) {
                    logger.error("post请求提交失败:" + url, e);
                }
            }
        } catch (IOException e) {
            logger.error("post请求提交失败:" + url, e);
        } finally {
            httpPost.releaseConnection();
        }
        return jsonResult;
    }

    /**
     * post请求传输String参数 例如：name=Jack&sex=1&type=2
     * Content-type:application/x-www-form-urlencoded
     *
     * @param url      url地址
     * @param strParam 参数
     * @return
     */
    public static JSONObject httpPost(String url, String strParam) {
        // post请求返回结果
        CloseableHttpClient httpClient = HttpClients.createDefault();
        JSONObject jsonResult = new JSONObject();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(requestConfig);
        try {
            if (null != strParam) {
                // 解决中文乱码问题
                StringEntity entity = new StringEntity(strParam, "utf-8");
                entity.setContentEncoding("UTF-8");
                entity.setContentType("application/x-www-form-urlencoded");
                httpPost.setEntity(entity);
            }
            CloseableHttpResponse result = httpClient.execute(httpPost);
            System.out.println(result);
            // 请求发送成功，并得到响应
            if (result.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                String str = "";
                try {
                    // 读取服务器返回过来的json字符串数据
                    str = EntityUtils.toString(result.getEntity(), "utf-8");
                    // 把json字符串转换成json对象
                    jsonResult = JSONObject.parseObject(str);
                } catch (Exception e) {
                    jsonResult.put("post请求提交失败:", url + "-->" + e);
                }
            }
        } catch (IOException e) {
            jsonResult.put("post请求提交失败:", url + "-->" + e);
        } finally {
            httpPost.releaseConnection();
        }
        return jsonResult;
    }

    /**
     * 发送get请求
     *
     * @param url 路径
     * @return
     */
    public static JSONObject httpGet(String url) {
        // get请求返回结果
        JSONObject jsonResult = new JSONObject();
        CloseableHttpClient client = HttpClients.createDefault();
        // 发送get请求
        HttpGet request = new HttpGet(url);
        request.setConfig(requestConfig);
        try {
            CloseableHttpResponse response = client.execute(request);

            // 请求发送成功，并得到响应
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                // 读取服务器返回过来的json字符串数据
                HttpEntity entity = response.getEntity();
                String strResult = EntityUtils.toString(entity, "utf-8");
                // 把json字符串转换成json对象
                jsonResult = JSONObject.parseObject(strResult);
            } else {
                logger.error("get请求提交失败:" + url);
                jsonResult.put("get请求提交失败:", url);
            }
        } catch (IOException e) {
            logger.error("get请求提交失败:" + url, e);
            jsonResult.put("get请求提交失败:", url + "-->" + e);
        } finally {
            request.releaseConnection();
        }
        return jsonResult;
    }

    /**
     * 发送自定义请求头的get请求
     *
     * @param host 路径
     * @return
     */
    public static JSONObject httpGetByCustomerHeader(String ip, String reqHeaderStr) throws Exception{
        // get请求返回结果
        JSONObject jsonResult = new JSONObject();
        CloseableHttpClient client = HttpClients.createDefault();
        // 发送get请求
        HttpGet request = new HttpGet(ip);
        request.setConfig(requestConfig);
        // 设置请求头
        Map<String, String> headers = MyStrignUtils.parseHeader(reqHeaderStr);
        if (headers != null && headers.size() > 0) {
            Set<String> keys = headers.keySet();
            for (String key : keys) {
                System.out.println(headers.get(key).replaceAll(" +",""));
                if (key.equalsIgnoreCase("Accept-Charset")){
                    // 如果是Accept-CharSet,进行Base64编码
                    request.setHeader(key,MyStrignUtils.base64Encode(headers.get(key)).replaceAll(" +",""));
                    continue;
                }
                request.setHeader(key,headers.get(key).replaceAll(" +",""));
            }
        }

        try {
            CloseableHttpResponse response = client.execute(request);
            // 读取服务器返回过来的json字符串数据
            HttpEntity entity = response.getEntity();
            String strResult = EntityUtils.toString(entity, "utf-8");
            // 把json放入json对象
            StatusLine ststus = response.getStatusLine();
            Header[] allHeaders = response.getAllHeaders();
            System.out.println("allHeaders::"+Arrays.toString(allHeaders));
            jsonResult.put("ststus", ststus.toString());
            jsonResult.put("headers", allHeaders);
            jsonResult.put("content", strResult);

        } finally {
            request.releaseConnection();
        }
        return jsonResult;
    }

    /**
     * 发送自定义请求头的get请求
     *
     * @param host 路径
     * @return
     */
    public static JSONObject httpPostByCustomerHeader(String ip, String reqHeaderStr)  throws Exception{
        // get请求返回结果
        JSONObject jsonResult = new JSONObject();
        CloseableHttpClient client = HttpClients.createDefault();
        // 发送get请求
        HttpPost request = new HttpPost(ip);
        request.setConfig(requestConfig);
        // 设置请求头
        Map<String, String> headers = MyStrignUtils.parseHeader(reqHeaderStr);
        if (headers != null && headers.size() > 0) {
            Set<String> keys = headers.keySet();
            for (String key : keys) {
                if (key.equalsIgnoreCase("Accept-Charset")){
                    // 如果是Accept-CharSet,进行Base64编码
                    request.setHeader(key,MyStrignUtils.base64Encode(headers.get(key)));
                    continue;
                }
                request.setHeader(key,headers.get(key));
            }
        }

        try {
            CloseableHttpResponse response = client.execute(request);
            // 读取服务器返回过来的json字符串数据
            HttpEntity entity = response.getEntity();
            String strResult = EntityUtils.toString(entity, "utf-8");
            // 把json放入json对象
            StatusLine ststus = response.getStatusLine();
            Header[] allHeaders = response.getAllHeaders();
            System.out.println("allHeaders::"+Arrays.toString(allHeaders));
            jsonResult.put("ststus", ststus.toString());
            jsonResult.put("headers", allHeaders);
            jsonResult.put("content", strResult);

        } catch (IOException e) {
            logger.error("get请求提交失败:" + ip, e);
            jsonResult.put("get请求提交失败:", ip + "-->" + e);
        } finally {
            request.releaseConnection();
        }
        return jsonResult;
    }
}
